function trim(str){
	if(str != null)
		return str.replace('/^\s+/', '').replace('/(\s+)$/', '');
	else
		return str;
}
var brd = null;
function executeJs(){
	if( brd != null){
		JXG.JSXGraph.freeBoard(brd);
		brd = JXG.JSXGraph.initBoard('jsxtextarea',{axis:true,boundingbox:[-5,5,5,-5]});
	}
	else{
		brd = JXG.JSXGraph.initBoard('jsxtextarea',{axis:true,boundingbox:[-5,5,5,-5]});
	}
	var codes = document.getElementById('codestextarea').value;
	if(codes == ""){
		alert("please input codes");
		return;
	}
	var codearray = codes.split("\n");
	var pureCode = "";
	for(var i=0; i<codearray.length;i++){
		var code = codearray[i];
		if(code.indexOf("//") > -1){
			code = code.substr(0, code.indexOf("//"));
		}else if( '' != code){
			code = trim(code);
		}
		pureCode += code +"\n";
	}
	try{
		eval(pureCode);
	}catch(exception){
		alert(exception);
	}
}

function sketchAllPics(){
	$(".codejxgbox").each(function(){
		var id = $(this).attr("id");
		var pro = "pro_" + id;
		board = JXG.JSXGraph.initBoard(pro, {boundingbox:[-10,10,10,-10], axis:false});
        board.jc = new JXG.JessieCode();
        board.jc.use(board);
        board.jc.parse($(this).val());
	});
}

function front_search_input(){
	$("#coursera-front-search-banner-input").bind({
		focusin:function(){
			if(trim($(this).val()) != ""){
				$(".coursera-front-autocomplete-menu").show();
			}
		},
		focusout:function(){
			$(".coursera-front-autocomplete-menu").hide();
		},
		keyup:function(){
			var value = trim($(this).val());
			if(value == ""){
				$(".coursera-front-autocomplete-menu").hide();
			}else{
				$.post("/search",{'type':1,'search':value},function(data){
					if(data.err == 0){
						var dat = data.data;
						var res = '<li><ul><li class="coursera-front-auto-li all-results active"><a href="javascript:void;" class="internal-home">See all results...</a></li></ul></li>';
						for(i in dat){
							res += '<li><h5>'+ i +'</h5><ul>';
							for(var k=0, len=dat[i].length; k<len; k++){
								var j = dat[i][k];
								res += '<li class="coursera-front-auto-li"><a href="/content?type='+ i +'&kid='+ j.id +'" tabindex="-1" class="internal-home">'+ j.name +'</a></li>';
							}
							res += '</ul></li>';
						}
						$(".coursera-front-autocomplete-menu").empty();
						$(".coursera-front-autocomplete-menu").append(res);
						$(".coursera-front-autocomplete-menu").show();
						$(".coursera-front-auto-li").bind({
							mousedown:function(){
								if($(this).hasClass("all-results")){
									$(".coursera-front-search-banner-form").submit();
								}else{
									window.location = $(this).children("a").attr("href");
								}
							},
							mouseover:function(){
								$(this).addClass("active");
							},
							mouseout:function(){
								$(this).removeClass("active");
							}
						});
					}
				}, 'json')
			}
		}
	});
}

function index_onload(){
	sketchAllPics();
	front_search_input();
}

var Class = {
	create : function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}
var Extend = function(destination, source) {
	for ( var property in source) {
		destination[property] = source[property];
	}
}
function stopDefault(e) {
	if (e && e.preventDefault) {
		e.preventDefault();
	} else {
		window.event.returnValue = false;
	}
	return false;
}

var Stars = Class.create();
Stars.prototype = {
	initialize : function(star, options) {
		this.SetOptions(options); //默认属性
		var flag = 999; //定义全局指针
		var isIE = (document.all) ? true : false; //IE?
		var starlist = document.getElementById(star).getElementsByTagName('a'); //星星列表
		var input = document.getElementById(this.options.Input)
				|| document.getElementById(star + "-input"); // 输出结果
		var tips = document.getElementById(this.options.Tips)
				|| document.getElementById(star + "-tips"); // 打印提示
		var nowClass = " " + this.options.nowClass; // 定义选中星星样式名
		var tipsTxt = this.options.tipsTxt; // 定义提示文案
		var len = starlist.length; //星星数量

		for (i = 0; i < len; i++) { // 绑定事件 点击 鼠标滑过
			starlist[i].value = i;
			starlist[i].onclick = function(e) {
				stopDefault(e);
				this.className = this.className + nowClass;
				flag = this.value;
				input.value = this.getAttribute("star:value");
				tips.innerHTML = tipsTxt[this.value]
			}
			starlist[i].onmouseover = function() {
				if (flag < 999) {
					var reg = RegExp(nowClass, "g");
					starlist[flag].className = starlist[flag].className
							.replace(reg, "")
				}
			}
			starlist[i].onmouseout = function() {
				if (flag < 999) {
					starlist[flag].className = starlist[flag].className
							+ nowClass;
				}
			}
		}
		;
		if (isIE) { //FIX IE下样式错误
			var li = document.getElementById(star).getElementsByTagName('li');
			for ( var i = 0, len = li.length; i < len; i++) {
				var c = li[i];
				if (c) {
					c.className = c.getElementsByTagName('a')[0].className;
				}
			}
		}
	},
	//设置默认属性
	SetOptions : function(options) {
		this.options = {//默认值
			Input : "",//设置触保存分数的INPUT
			Tips : "",//设置提示文案容器
			nowClass : "current-rating",//选中的样式名
			tipsTxt : [ "Terrible", "Poor", "Average", "Very Good", "Excellent" ]
		//提示文案
		};
		Extend(this.options, options || {});
	}
}

function knowledge_rating(){
	$(".knowledge-rating-level").each(function(){
		var id = $(this).attr('know_id');
		new Stars(id);
		$(this).bind('click', function(){
			var self = $(this);
			var li = id.split("_");
			var va = $("#"+id+"-input").val();
			var va2 = $("#"+id+"-text-comments").val();
			$.post("/point",{'resource':li[0],'rid':li[1],'value':va, 'comment': va2},function(data){
				if(data.err == 0){
					self.attr('value','Done');					
				}
			}, 'json');
		})
	})
}

function loca_change(){
	var va = $("#contents_search").attr("search_cont");
	var types = [];
	$("input[name='knowledge2']").each(function(){
		if(this.checked){
			types.push(this.value);
		}
	});
	var sort = $("select[name='sortby']")[0].value;
	types = types.join(",");
	window.location.href = "/contents?search="+va+"&type="+types+"&sortby="+sort;
}

function contents_onload(){
	$("#contents_search_btn").bind('click', function(){
		$("#contents_search").attr("search_cont", $("#contents_search").val());
		loca_change();
	});
	$("input[name='knowledge2']").bind('click', loca_change);
	$("select[name='sortby']").bind('change', loca_change);
}

//function MM_CheckFlashVersion(reqVerStr,msg){
//  with(navigator){
//    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
//    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
//    if (!isIE || !isWin){  
//      var flashVer = -1;
//      if (plugins && plugins.length > 0){
//        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
//        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
//        if (desc == "") flashVer = -1;
//        else{
//          var descArr = desc.split(" ");
//          var tempArrMajor = descArr[2].split(".");
//          var verMajor = tempArrMajor[0];
//          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
//          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
//          flashVer =  parseFloat(verMajor + "." + verMinor);
//        }
//      }
//      // WebTV has Flash Player 4 or lower -- too low for video
//      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;
//
//      var verArr = reqVerStr.split(",");
//      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
//  
//      if (flashVer < reqVer){
//        if (confirm(msg))
//          window.location = "http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
//      }
//    }
//  }
//}

function check_full_name(){
	var val = $("#coursera-signup-fullname").val();
	$("#signup-duplicate").addClass("hide");
	if( trim(val)!="" ){
		$("#coursera-signup-fullname-help").text($("#coursera-signup-fullname").attr("data-form-correct"));
		$("#coursera-signup-fullname").parent().parent().addClass("success");
		$("#coursera-signup-fullname").parent().parent().removeClass("error");
		return true;
	}else{
		$("#coursera-signup-fullname-help").text($("#coursera-signup-fullname").attr("data-form-error"));
		$("#coursera-signup-fullname").parent().parent().removeClass("success");
		$("#coursera-signup-fullname").parent().parent().addClass("error");
		return false;
	}
}

function check_email(){
	var val = $("#coursera-signup-email").val();
	var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
	if( reg.test(val) ){
		$("#coursera-signup-email-help").text($("#coursera-signup-email").attr("data-form-correct"));
		$("#coursera-signup-email").parent().parent().addClass("success");
		$("#coursera-signup-email").parent().parent().removeClass("error");
		return true;
	}else{
		$("#coursera-signup-email-help").text($("#coursera-signup-email").attr("data-form-error"));
		$("#coursera-signup-email").parent().parent().removeClass("success");
		$("#coursera-signup-email").parent().parent().addClass("error");
		return false;
	}
}

function check_pass(){
	var val = $("#coursera-signup-password").val();
	if( val.length > 3 ){
		$("#coursera-signup-password-help").text($("#coursera-signup-password").attr("data-form-correct"));
		$("#coursera-signup-password").parent().parent().addClass("success");
		$("#coursera-signup-password").parent().parent().removeClass("error");
		return true;
	}else{
		$("#coursera-signup-password-help").text($("#coursera-signup-password").attr("data-form-error"));
		$("#coursera-signup-password").parent().parent().removeClass("success");
		$("#coursera-signup-password").parent().parent().addClass("error");
		return false;
	}
}

function check_pass_again(){
	var val = $("#coursera-signup-password-confirm").val();
	var val2 = $("#coursera-signup-password").val();
	check_pass();
	if( val == val2 ){
		$("#coursera-signup-password-confirm-help").text($("#coursera-signup-password-confirm").attr("data-form-correct"));
		$("#coursera-signup-password-confirm").parent().parent().addClass("success");
		$("#coursera-signup-password-confirm").parent().parent().removeClass("error");
		return true;
	}else{
		$("#coursera-signup-password-confirm-help").text($("#coursera-signup-password-confirm").attr("data-form-error"));
		$("#coursera-signup-password-confirm").parent().parent().removeClass("success");
		$("#coursera-signup-password-confirm").parent().parent().addClass("error");
		return false;
	}
}

function check_agree(){
	if( $("#coursera-signup-agree")[0].checked ){
		$("#coursera-signup-terms-help").addClass("hide");
		$("#coursera-signup-agree").parent().parent().parent().removeClass("error");
		return true;
	}else{
		$("#coursera-signup-terms-help").removeClass("hide");
		$("#coursera-signup-agree").parent().parent().parent().addClass("error");
		return false;
	}
}

function signup_onload(){
	$("#coursera-signup-fullname").focusout(check_full_name);
	$("#coursera-signup-email").focusout(check_email);
	$("#coursera-signup-password").focusout(check_pass);
	$("#coursera-signup-password-confirm").focusout(check_pass_again);
	$("#coursera-signup-agree").change(check_agree);
	$("button[type='submit']").click(function(){
		if(check_full_name() && check_email() && check_pass() && check_pass_again() && check_agree()){
			$("form").submit();
		}
	});
}

function check_signin(){
	var val1 = $("#signin-email").val();
	var val2 = $("#signin-password").val();
	var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
	if( reg.test(val1) && val2.length > 3 ){
		$("#signin-fail").addClass("hide");
		return true;
	}else{
		$("#signin-fail").removeClass("hide");
		return false;
	}
}

function signin_onload(){
	$("button[type='submit']").click(function(){
		if( check_signin() ){
			$.post("/account/signin",{'email':$("#signin-email").val(),'password':$("#signin-password").val()},function(data){
				if(data.err == 0){
					if(data.data == 0){
						$("#signin-fail").removeClass("hide");
					}else{
						window.location = "/users?i="+data.data;
					}
				}
			}, 'json');
		}
	});
}

function header_popup(){
	$("#all-header-about-pop").bind({
		click:function(){
			$("#coursera-header-about-popup").show();
			$("#coursera-header-about-popup").css('left', $("#all-header-about-pop").offset().left)
		},
		focusout:function(ent){
			$("#coursera-header-about-popup").hide();
		}
	});
	$("#coursera-header-about-popup").bind({
		mouseover:function(){
			$(this).show();
		},
		mouseout:function(){
			$(this).hide();
		}
	});
	$("#coursera-header-about-popup").children("a").bind('mousedown', function(ent){
		window.location = $(this).attr('href');
	});
	
	$("#all-header-account-pop").bind({
		click:function(){
			$("#coursera-header-account-popup").show();
			var left = $("#all-header-account-pop").offset().left+$("#all-header-account-pop").outerWidth()-$("#coursera-header-account-popup").outerWidth();
			$("#coursera-header-account-popup").css('left', left);
		},
		focusout:function(ent){
			$("#coursera-header-account-popup").hide();
		}
	});
	$("#coursera-header-account-popup").bind({
		mouseover:function(){
			$(this).show();
		},
		mouseout:function(){
			$(this).hide();
		}
	});
	$("#coursera-header-account-popup").children("a").bind('mousedown', function(ent){
		window.location = $(this).attr('href');
	});
}

$(document).ready(header_popup);

function knowledgeman_onload(){
	$("#knows-equiv-pop").click(function(){
		if( $(this).attr('data-ajax') == '0'){
			$.post("/knowsame",{'type':1,'knowledge':$(this).attr('know-type')},function(data){
				if(data.err == 0){
					var str = "";
					for(var k=0, len=data.data.length; k<len; k++){
						str += '<option value="'+ data.data[k].id +'">'+ data.data[k].name +'</option>';
					}
					$("#knows-equiv-values").append(str);
					$("#knows-equiv-pop").attr('data-ajax', '1');
				}
			}, 'json');
		}
		if( $(this).attr('data-open') == '0'){
			$("#knows-equiv-pop-div").show();
			$(this).attr('data-open', '1');
		}else{
			$("#knows-equiv-pop-div").hide();
			$(this).attr('data-open', '0');
		}
	});
	$("#knows-equiv-submit").click(function(){
		var name1 = $("#knows-equiv-values").val();
		if(name1 == "notexists"){
			$("#knows-equiv-knowid").attr('value', '0');
			$("#knows-equiv-tips-1").text("");
			$("#knows-equiv-tips").text("not exists in db");
			return;
		}
		$("#knows-equiv-knowid").attr('value', name1);
		$("#knows-equiv-tips-1").text( $("#knows-equiv-values").children(":selected").text() );
		$("#knows-equiv-tips").text("select ok");
	});
}

function files_change_record( type ){
	var ids = [];
	$(".change-"+type).each(function(){
		if($(this).children("a").attr("data-select") != "0"){
			ids.push($(this).attr("data-type-id"));
		}
	});
	if(ids.length == 0){
		$("#change"+type).attr("value", "0");
	}else{
		$("#change"+type).attr("value", ids.join(","));
	}
}


function reuse_onload(){
	$(".nofiles-popup").click(function(){
		var objid = $(this).attr('data-popup-obj');
		if( $(this).attr('data-open') == '0'){
			$(this).siblings("p").hide();
			$("#"+objid).show();
			$(this).attr('data-open', '1');
		}else{
			$(this).siblings("p").show();
			$("#"+objid).hide();
			$(this).attr('data-open', '0');
		}
	});
	$(".change-flag-parent").children().change(function(){
		var objid = $(this).parent().attr('data-change-obj');
		$("#"+objid).attr('value', '0');
	});
	files_change_record("Image");
	files_change_record("Audio");
	files_change_record("Video");
	$(".change-all-select").click(function(){
		var type = $(this).parent().attr("data-type");
		if($(this).attr("data-select") == "0"){
			$(this).children("span").text("delete this "+type);
			$(this).prev().attr("src", "/static/images/dui50.jpg");
			$(this).attr("data-select", "1");
		}else{
			$(this).children("span").text("reuse this "+type);
			$(this).prev().attr("src", "/static/images/cuo50.jpg");
			$(this).attr("data-select", "0");
		}
		files_change_record(type);
	})
	
}

//
//function knowsametest(){
//	$("#knows-equiv-submit").click(function(){
//		var name1 = $("#knows-equiv-values").val();
//		var name2 = $("#knows-equiv-name").val();
//		if(name1 == "notexists"){
//			$("#knows-equiv-tips").text("not exists in db");
//			return;
//		}
//		if(name2 == ""){
//			$("#knows-equiv-tips").text("knowledge name must be a string");
//			return;
//		}
//		if(name1 == name2){
//			$("#knows-equiv-tips").text("two names canot be the same");
//			return;
//		}
//		$.post("/knowsame",{'type':2,'name1':name1,'name2':name2,'knowledge':$("#knows-equiv-pop").attr('know-type')},function(data){
//			if(data.err == 0){
//				$("#knows-equiv-submit").attr('value','Done');
//				$("#knows-equiv-tips").text("insert ok");
//			}
//		}, 'json');
//	});
//}

